package com.arm.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.arm.def.Constant;
import com.arm.module.AdminUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Andrew  on 2016/12/29.
 */
public class AuthorityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("text/html;charset=utf-8");
        httpServletRequest.setCharacterEncoding("UTF-8");
        HttpSession session=httpServletRequest.getSession();
        AdminUser adminUser=(AdminUser) session.getAttribute(Constant.SESSION_KEY_ADMIN_USER_LOGIN);
        if (adminUser!=null){
            return true;
        }
        String requestType = httpServletRequest.getHeader("X-Requested-With");
        if (requestType!=null&&requestType.equals("XMLHttpRequest")){
        JSONObject result=new JSONObject();
        result.put("result",0);
        result.put("reason","请登录");
        httpServletResponse.getWriter().write(result.toJSONString());
        }else {
            System.out.println("qing");
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/admin/user/gotoLogin");
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
